package com.wcl.demo.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;

import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.search.core.PoiInfo;
import com.easemob.EMCallBack;
import com.easemob.EMEventListener;
import com.easemob.EMNotifierEvent;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.chat.EMMessage;
import com.easemob.chat.ImageMessageBody;
import com.easemob.chat.LocationMessageBody;
import com.easemob.chat.NormalFileMessageBody;
import com.easemob.chat.TextMessageBody;
import com.easemob.chat.VoiceMessageBody;
import com.wcl.demo.R;
import com.wcl.demo.db.BackGroundHelper;
import com.wcl.demo.db.CanSendHelper;
import com.wcl.demo.model.entity.BackGroundData;
import com.wcl.demo.model.entity.SearchHimUser;
import com.wcl.demo.ui.activity.java.ChatEmoji;
import com.wcl.demo.ui.adapter.AddClickInforAdapter;
import com.wcl.demo.ui.adapter.ChatAdapter;
import com.wcl.demo.ui.adapter.FaceAdapter;
import com.wcl.demo.ui.adapter.ViewPagerAdapter;
import com.wcl.demo.ui.fragment.ItemInterface.AddClickItemListener;
import com.wcl.demo.utils.ActivityUtils;
import com.wcl.demo.utils.FaceConversionUtil;
import com.wcl.demo.view.CustomToast;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.easemob.util.FileUtils.getMIMEType;

/**
 * Created by dllo on 15/11/23.
 */
public class ChatActivity extends Activity implements EMEventListener, AdapterView.OnItemClickListener, AddClickItemListener {

    private LinearLayout activity_chat_linerLayout;
    private String username;//用户名
    private String title;//聊天界面标题
    private boolean groupchat;//判断是否为群聊
    private EMConversation conversation;//聊天对话
    private List<EMMessage> list;//消息列表
    private ChatAdapter adapter;//聊天适配器
    private MediaRecorder recorder;//录音
    private boolean pressDown = false;//判断录音按钮是否是按下状态
    private RecyclerView recyclerView;//定义RecyclerView
    private AddClickInforAdapter inforAdapter;//定义点击加号的adapter
    private String headimageurl;//定义Parse头像地址
    private int[] imgs = {R.mipmap.iconfont_files, R.mipmap.iconfont_xiangjis,
            R.mipmap.iconfont_tupians, R.mipmap.iconfont_weizhis};//定义加好内的图标数组

    private BackGroundHelper backGroundHelper;//背景帮助类
    private List<BackGroundData> backGroundDataList;//定义背景实体类

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            refresh();//刷新列表
            return false;
        }
    });
    private CanSendHelper canSendHelper;//定义发送名片帮助类

    @Bind(R.id.addIv)
    ImageView addIv;//加号按钮
    @Bind(R.id.chattext)
    EditText chattext;
    @Bind(R.id.chat_listView)
    ListView chat_listView;//聊天列表
    @Bind(R.id.voiceIv)
    ImageView voiceIv;//语音
    @Bind(R.id.keyboardIv)
    ImageView keyboardIv;//键盘
    @Bind(R.id.sendBtn)
    Button sendBtn;//发送按钮
    @Bind(R.id.holdToTalkBtn)
    Button holdToTalkBtn;//点击发送语音
    @Bind(R.id.chatTitle)
    TextView chatTitle;
    @Bind(R.id.holdToTalkPressBtn)
    Button holdToTalkPressBtn;//按下点击发送语音
    @Bind(R.id.chatedit_layout)
    LinearLayout chatedit_layout;
    @Bind(R.id.trash_sigle_notes)
    ImageView trash_sigle_notes;//删除一个人的记录
    @Bind(R.id.see_chat_person)
    ImageView see_chat_person;//群组列表中查看群成员信息图标

    //点击键盘,切换成语音
    @OnClick(R.id.keyboardIv)
    public void setkeyboardIv() {

        if (keyboardIv.getVisibility() == View.VISIBLE) {
            keyboardIv.setVisibility(View.GONE);
            voiceIv.setVisibility(View.VISIBLE);
            view.setVisibility(View.GONE);
            chatedit_layout.setVisibility(View.GONE);
            holdToTalkBtn.setVisibility(View.VISIBLE);
        }
    }

    //点击语音,切换成语音
    @OnClick(R.id.voiceIv)
    public void setYuyinIv() {
        if (voiceIv.getVisibility() == View.VISIBLE) {
            keyboardIv.setVisibility(View.VISIBLE);
            voiceIv.setVisibility(View.GONE);
            chatedit_layout.setVisibility(View.VISIBLE);
            holdToTalkBtn.setVisibility(View.GONE);
        }
    }

    //点击加号按钮,弹出recyclerView可以发送图片等
    @OnClick(R.id.addIv)
    void setaddIv() {
        if (recyclerView.getVisibility() == View.VISIBLE) {
            /** 关闭软键盘 **/
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
            mInputMethodManager.hideSoftInputFromWindow(chattext.getWindowToken(), 0);
            recyclerView.setVisibility(View.GONE);

        } else {
            /** 关闭软键盘 **/
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
            mInputMethodManager.hideSoftInputFromWindow(chattext.getWindowToken(), 0);
            recyclerView.setVisibility(View.VISIBLE);
            view.setVisibility(View.GONE);
        }
    }

    //点击发送按钮,发送文字
    @OnClick(R.id.sendBtn)
    public void sendBtn(View v) {
        if (chattext == null || chattext.getText().toString().equals("")) {
            CustomToast.toastShow(this, "发送的消息不能为空");

        } else {
            //调用发送文字的方法
            sendTextBody();
        }
    }

    //点击垃圾桶,清空聊天记录
    @OnClick(R.id.trash_sigle_notes)
    public void setTrash_sigle_notes() {
        deleteNotesForChat(username);
    }

    /****
     * 清除单个当前用户的整个聊天记录
     */
    private void deleteNotesForChat(String username) {
        EMChatManager.getInstance().deleteConversation(username);
    }

    private InputMethodManager mInputMethodManager;//定义键盘管理者

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayout());
        mInputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        ButterKnife.bind(this);
        initView();
        initData();
    }


    @OnClick(R.id.chattext)
    public void setChattext() {
        recyclerView.setVisibility(View.GONE);
    }

    //加载布局

    protected int getLayout() {
        return R.layout.activity_chat;
    }

    SearchHimUser user;
    protected void initView() {
        backGroundHelper = new BackGroundHelper();
        backGroundDataList = backGroundHelper.queryAll();
        //判断是否设置过背景图片
        if (backGroundDataList != null && backGroundDataList.size() > 0) {
            //地址->bitmap->draw
            Drawable drawable = new BitmapDrawable(BitmapFactory.decodeFile(backGroundDataList.get(0).getPictureKey()));
            //改变布局背景图片
            activity_chat_linerLayout = (LinearLayout) findViewById(R.id.activity_chat_linerLayout);
            activity_chat_linerLayout.setBackgroundDrawable(drawable);
        }

        keyboardIv = (ImageView) findViewById(R.id.keyboardIv);
        inforAdapter = new AddClickInforAdapter();
        recyclerView = (RecyclerView) findViewById(R.id.jiahao_recyclerView);
        GridLayoutManager manager = new GridLayoutManager(this, 4);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(inforAdapter);
        inforAdapter.setAddItemClick(this);

        view = findViewById(R.id.ll_facechoose);
        emojis = FaceConversionUtil.getInstace().emojiLists;
        onCreate();

        Log.i("lanou", "表情" + emojis.size() + "**********");

        //接收跳转后传进来的用户的id
        Bundle bundle = ActivityUtils.fromSrc(this);
        this.username = bundle.getString("username");
        this.groupchat = bundle.getBoolean("groupchat");
        this.headimageurl = bundle.getString("headimageurl");
        Log.i("headimageurl" , headimageurl + "");


        if (bundle.getString("title") != null) {
            Log.i("wclop",bundle.getString("title")+" <--");
            this.title = bundle.getString("title");
            chatTitle.setText(title);
        } else {
            chatTitle.setText(username);
        }
        if (groupchat) {
            trash_sigle_notes.setVisibility(View.GONE);
            see_chat_person.setVisibility(View.VISIBLE);
        } else {
            trash_sigle_notes.setVisibility(View.VISIBLE);
            see_chat_person.setVisibility(View.GONE);
        }
        EMChat.getInstance().setAppInited();
        Log.i("lanou", "----->>>" + username);
        conversation = EMChatManager.getInstance().getConversation(username);
        final List<EMMessage> emMessages = conversation.getAllMessages();
        Log.i("jkkjk", emMessages + "");
        adapter = new ChatAdapter(this);
        adapter.addData(emMessages , headimageurl);
        Log.i("jhdfgjkkjldfg", "第一次");
        chat_listView.setAdapter(adapter);
        chat_listView.setSelection(emMessages.size());

        holdToTalkBtn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        pressDown = true;
                        holdToTalkPressBtn.setVisibility(View.VISIBLE);
                        holdToTalkBtn.setVisibility(View.GONE);
                        recyclerView.setVisibility(View.GONE);
                        break;
                    case MotionEvent.ACTION_UP:
                        pressDown = false;
                        holdToTalkPressBtn.setVisibility(View.GONE);
                        holdToTalkBtn.setVisibility(View.VISIBLE);
                        recyclerView.setVisibility(View.GONE);
                        break;
                }
                return false;
            }
        });

        see_chat_person.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle1 = new Bundle();
                bundle1.putString("groupid", username);
                ActivityUtils.startToActivity(ChatActivity.this, GroupMsgActivity.class, bundle1);
            }
        });

        /***改变发送按钮和加号***/
        chattext.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if (!TextUtils.isEmpty(s)) {
                    sendBtn.setVisibility(View.VISIBLE);
                    keyboardIv.setVisibility(View.GONE);
                    voiceIv.setVisibility(View.GONE);

                } else {
                    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
                    mInputMethodManager.hideSoftInputFromWindow(chattext.getWindowToken(), 0);
                    chat_listView.setSelection(emMessages.size());
                    sendBtn.setVisibility(View.GONE);
                    keyboardIv.setVisibility(View.VISIBLE);
                    voiceIv.setVisibility(View.GONE);

                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    protected void initData() {

        new Thread(new Runnable() {
            boolean hasRecord = false;

            @Override
            public void run() {
                while (true) {
                    if (pressDown && !hasRecord) {
                        //按下的时候开始录音
                        soundRecording();
                        hasRecord = true;
                        Log.i("Sysout", "down");
                    } else {
                        //抬起的时候发送并停止录音
                        if (hasRecord && recorder != null && !pressDown) {
                            Log.i("Sysout", "up");
                            hasRecord = false;
                            try {
                                sendSoundBody();
                                recorder.stop();
                                recorder.release();
                                recorder = null;
                            } catch (IllegalStateException e) {
                                e.printStackTrace();
                            }
                            Log.i("lanou", "录音结束");
                        }
                    }
                }
            }
        }).start();

        EMChat.getInstance().setAppInited();
        EMChatManager.getInstance().getChatOptions().setShowNotificationInBackgroud(true);
        EMChatManager.getInstance().registerEventListener(this, new EMNotifierEvent.Event[]{EMNotifierEvent.Event.EventNewCMDMessage,
                EMNotifierEvent.Event.EventNewMessage, EMNotifierEvent.Event.EventOfflineMessage, EMNotifierEvent.Event.EventConversationListChanged});
    }

    /****************************************y语音**************************************************/
    /****
     * 开始录音
     */
    private String fileName;

    private void soundRecording() {
        recorder = new MediaRecorder();// new出MediaRecorder对象
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        // 设置MediaRecorder的音频源为麦克风
        recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
        // 设置MediaRecorder录制的音频格式
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
        // 设置MediaRecorder录制音频的编码为amr.
        recorder.setOutputFile("/sdcard/" + System.currentTimeMillis() + ".mp3");
        // 设置录制好的音频文件保存路径
        fileName = "/sdcard/" + System.currentTimeMillis() + ".mp3";
        Log.i("EMMessageUtils", fileName);
        try {
            recorder.prepare();// 准备录制
            recorder.start();// 开始录制
            Log.i("lanou", "开始录音");

        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /***
     * 发送语音
     */
    private void sendSoundBody() {
        String filepath = fileName;
        EMConversation emConversation = EMChatManager.getInstance().getConversation(username);
        EMMessage emMessage = EMMessage.createSendMessage(EMMessage.Type.VOICE);
        if (groupchat) {
            emMessage.setChatType(EMMessage.ChatType.GroupChat);
        } else {
            emMessage.setChatType(EMMessage.ChatType.Chat);
        }
        int a = filepath.length();
        VoiceMessageBody body = new VoiceMessageBody(new File(filepath), a);
        emMessage.addBody(body);
        emMessage.setReceipt(username);
        emConversation.addMessage(emMessage);
        EMChatManager.getInstance().sendMessage(emMessage, new EMCallBack() {
            @Override
            public void onSuccess() {
                Log.i("lanou", "成功 *******");
                handler.sendEmptyMessage(200);
            }

            @Override
            public void onError(int i, String s) {

            }

            @Override
            public void onProgress(int i, String s) {

            }
        });
    }

    /****************************************文字**************************************************/

    /****
     * 发送文字
     */
    private void sendTextBody() {
        //获取到与聊天人的会话对象。参数username为聊天人的userid或者groupid，后文中的username皆是如此
        EMConversation conversation = EMChatManager.getInstance().getConversation(username);
        //创建一条文本
//        EMMessage message = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
        EMMessage message = EMMessage.createSendMessage(EMMessage.Type.TXT);
        //单聊  //如果是群聊，设置chattype,默认是单聊
        if (groupchat) {
            message.setChatType(EMMessage.ChatType.GroupChat);
        }
        TextMessageBody textMessageBody = new TextMessageBody(chattext.getText().toString());
        message.addBody(textMessageBody);
        //设置接收人
        message.setReceipt(username);
        // 把消息加入到此会话对象中
        conversation.addMessage(message);
        EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
                    @Override
                    public void onSuccess() {
                        Log.i("lanou", "成功 *******");
                    }

                    @Override
                    public void onError(int i, String s) {

                        Log.i("lanou", "失败 *******");
                    }

                    @Override
                    public void onProgress(int i, String s) {

                        Log.i("lanou", "不知道什么意思 *******");
                    }
                }
        );
        refresh();
        chattext.setText("");

    }

    /***
     * 来消息的时候需要刷新列表
     */
    public void refresh() {

        EMChat.getInstance().setAppInited();
        conversation = EMChatManager.getInstance().getConversation(username);
        conversation.markAllMessagesAsRead();
        list = conversation.getAllMessages();

        adapter.addData(list , headimageurl);
        chat_listView.setSelection(list.size());
        if (groupchat && list.size() > 0) {
            for (EMGroup emGroup : EMGroupManager.getInstance().getAllGroups()) {
                if (emGroup.getGroupId().equals(list.get(0).getUserName())) {
                    chatTitle.setText(emGroup.getGroupName());
                }
            }
        }
        //EMChat.getInstance().setAppInited();
    }

    @Override
    public void onEvent(EMNotifierEvent emNotifierEvent) {
        EMMessage message = (EMMessage) emNotifierEvent.getData();
        switch (emNotifierEvent.getEvent()) {
            case EventNewCMDMessage:
                Log.i("lanou999", "EventNewCMDMessage");
                handler.sendEmptyMessage(1000);
                //   refresh();
                break;
            case EventNewMessage:
                Log.i("lanou999", "EventNewMessage");
                handler.sendEmptyMessage(2000);
                //  refresh();
                break;
            case EventOfflineMessage:
                Log.i("lanou999", "EventOfflineMessage");
                handler.sendEmptyMessage(3000);
                // refresh();
                break;
            case EventConversationListChanged:
                Log.i("lanou999", "EventConversationListChanged");
                handler.sendEmptyMessage(4000);
                //  refresh();
                break;
        }
    }

    @OnClick(R.id.chat_back)
    void chat_back(View v) {
        finish();
    }

    /***
     * 点击图片按钮
     **/

    @Override
    public void setAddClickItemClickListener(int img) {
        switch (img) {
            case R.mipmap.iconfont_tupians:
                selectImage();
                break;
            case R.mipmap.iconfont_files:
                selectFile();
                break;
            case R.mipmap.iconfont_xiangjis:
                selectCamera();
                break;
            case R.mipmap.iconfont_weizhis:
                selectLocation();
                break;
            case R.mipmap.iconfont_mycard:
//                selectLocation();
                sendCard();
                break;
        }
    }
    /***********************
     * 发送名片
     */
    public void sendCard(){
        canSendHelper=new CanSendHelper();
        if (canSendHelper.queryAll()!=null&&canSendHelper.queryAll().size()>0) {
            String myMessage = canSendHelper.queryAll().get(0).getCanSend();
            myMessage = myMessage.replace(" ", "\n");

            Log.i("shaco", myMessage + "<<<<<<<<<<<<<-------------");


            //获取到与聊天人的会话对象。参数username为聊天人的userid或者groupid，后文中的username皆是如此
            EMConversation conversation = EMChatManager.getInstance().getConversation(username);
            //创建一条文本
//        EMMessage message = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
            EMMessage message = EMMessage.createSendMessage(EMMessage.Type.TXT);
            //单聊  //如果是群聊，设置chattype,默认是单聊
            if (groupchat) {
                message.setChatType(EMMessage.ChatType.GroupChat);
            }
            TextMessageBody textMessageBody = new TextMessageBody(myMessage);
            message.addBody(textMessageBody);
            //设置接收人
            message.setReceipt(username);
            // 把消息加入到此会话对象中
            conversation.addMessage(message);
            EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
                        @Override
                        public void onSuccess() {
                            Log.i("lanou", "成功 *******");
                        }

                        @Override
                        public void onError(int i, String s) {

                            Log.i("lanou", "失败 *******");
                        }

                        @Override
                        public void onProgress(int i, String s) {

                            Log.i("lanou", "不知道什么意思 *******");
                        }
                    }
            );
            refresh();
            chattext.setText("");
        }else {
            Toast.makeText(this,"请先进行名片设置",Toast.LENGTH_SHORT).show();
        }



    }


    /***********************************************
     * 位置
     ********************************************/
    private void selectLocation() {
        Intent intent = new Intent(this, LocationActivity.class);
        intent.putExtra("username", username);
        startActivityForResult(intent, 600);
    }

    public void sendLocation(PoiInfo info) {
        EMConversation conversation = EMChatManager.getInstance().getConversation(username);
        EMMessage message = EMMessage.createSendMessage(EMMessage.Type.LOCATION);
        //如果是群聊，设置chattype,默认是单聊
        // message.setChatType(EMMessage.ChatType.GroupChat);
        LocationMessageBody locBody = new LocationMessageBody(info.address, info.location.latitude, info.location.longitude);
        message.addBody(locBody);
        message.setReceipt(username);
        conversation.addMessage(message);
        EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
            @Override
            public void onSuccess() {
                Log.i("android", "发送位置成功");
            }

            @Override
            public void onError(int i, String s) {

            }

            @Override
            public void onProgress(int i, String s) {

            }
        });
        refresh();
    }

    /***************************************************
     * 相机
     ****************************************/


     /* 头像文件 */
    private static final String IMAGE_FILE_NAME = "temp_head_image.jpg";

    /**
     * 检查设备是否存在SDCard的工具方法
     */
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            // 有存储的SDCard
            return true;
        } else {
            return false;
        }
    }

    /***
     * 选择相机图片
     */
    private void selectCamera() {
        Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        // 判断存储卡是否可用，存储照片文件
        if (hasSdcard()) {
            intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, Uri
                    .fromFile(new File(Environment
                            .getExternalStorageDirectory(), IMAGE_FILE_NAME)));
        }

        startActivityForResult(intentFromCapture, 300);
    }


    /**
     * 裁剪原始的图片
     */
    public void cropRawPhoto(Uri uri) {

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");

        // 设置裁剪
        intent.putExtra("crop", "true");

        // aspectX , aspectY :宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        // outputX , outputY : 裁剪图片宽高
        intent.putExtra("outputX", 120);
        intent.putExtra("outputY", 120);
        intent.putExtra("return-data", true);

        startActivityForResult(intent, 400);
    }

    /******************************************文件************************************************/

    /****
     * 选择文件
     */
    private void selectFile() {
        Intent intent = null;
        if (Build.VERSION.SDK_INT < 19) { //19以后这个api不可用，demo这里简单处理成图库选择图片
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);

        } else {
            intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
//        startActivityForResult(intent, 500);
//        Intent intentFile = new Intent();
//        intentFile.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        //设置intent的action属性
//        intentFile.setAction(Intent.ACTION_VIEW);
//        File file = new File();
//        //获取文件file的MIME类型
//        String type = getMIMEType(file);
//        //设置intent的data和Type属性
//        intentFile.setDataAndType(/*uri*/Uri.fromFile(file), type);
//        //跳转
//        Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
//        openAlbumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "file/*");
        startActivityForResult(intent, 500);
    }


    /**
     * 根据uri发送文件
     *
     * @param uri
     */
    protected void sendFileByUri(Uri uri) {
        String filePath = null;
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = null;

            try {
                cursor = this.getContentResolver().query(uri, filePathColumn, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    filePath = cursor.getString(column_index);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            filePath = uri.getPath();
        }
        File file = new File(filePath);
        if (file == null || !file.exists()) {
            CustomToast.toastShow(this, "文件不存在");
            return;
        }
        //大于10M不让发送
        if (file.length() > 10 * 1024 * 1024) {
            CustomToast.toastShow(this, "文件数据过大");
            return;
        }
        sendFileMessage(filePath);
    }

    /***
     * 发送文件
     *
     * @param filePath
     */
    private void sendFileMessage(String filePath) {
        EMConversation conversation = EMChatManager.getInstance().getConversation(username);
        // 创建一个文件消息
        EMMessage message = EMMessage.createSendMessage(EMMessage.Type.FILE);
        if (groupchat) {
            message.setChatType(EMMessage.ChatType.GroupChat);
        }
        // 如果是群聊，设置chattype,默认是单聊
        // add message body
        NormalFileMessageBody body = new NormalFileMessageBody(new File(filePath));
        message.addBody(body);
        //设置接收人的username
        message.setReceipt(username);
        conversation.addMessage(message);
        EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
            @Override
            public void onSuccess() {
                //  handler.sendEmptyMessage(2000);
            }

            @Override
            public void onError(int i, String s) {

            }

            @Override
            public void onProgress(int i, String s) {

            }
        });
        refresh();
    }


    /************************************************图片********************************************************************/
    /*****
     * 选择图片
     */
    public void selectImage() {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
        } else {
            intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, 200);
    }

    /**
     * 根据图库图片uri发送图片
     *
     * @param
     */
    protected void sendPicByUri(Uri picture) {
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = this.getContentResolver().query(picture, filePathColumn, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            cursor = null;
            if (picturePath == null || picturePath.equals("null")) {
                Toast toast = Toast.makeText(this, "找不到图片", Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                return;
            }
            sendImage(picturePath);
        } else {
            File file = new File(picture.getPath());
            if (!file.exists()) {
                Toast toast = Toast.makeText(this, "找不到图片", Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                return;
            }
            sendImage(file.getAbsolutePath());
        }

    }

    /*****
     * 发送图片
     */

    public void sendImage(String picture) {

        EMConversation conversation = EMChatManager.getInstance().getConversation(username);
        EMMessage message = EMMessage.createSendMessage(EMMessage.Type.IMAGE);
        //如果是群聊，设置chattype,默认是单聊
        if (groupchat) {
            message.setChatType(EMMessage.ChatType.GroupChat);
        }
        ImageMessageBody body = new ImageMessageBody(new File(String.valueOf(picture)));
        // 默认超过100k的图片会压缩后发给对方，可以设置成发送原图
        // body.setSendOriginalImage(true);
        message.addBody(body);
        message.setReceipt(username);
        //发送消息
        EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
            @Override
            public void onSuccess() {
                Log.i("searchHim", "成功 *******");
                Log.i("searchHim", "选择图片");
            }

            @Override
            public void onError(int i, String s) {

            }

            @Override
            public void onProgress(int i, String s) {

            }
        });
refresh();
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
//            case 2000:
//                if (data != null&&"".equals(data.getStringExtra("newTitle"))) {
//                    String newTitle=data.getStringExtra("newTitle");
//                    chatTitle.setText(newTitle);
//                }else{
//                    chatTitle.setText(title);
//                }
//                break;
            case 200:
                if (data != null) {
                    Uri picture = data.getData();
                    if (picture != null) {
                        sendPicByUri(picture);
                    }
                }
                break;
            case 300:
                if (hasSdcard()) {
                    File tempFile = new File(
                            Environment.getExternalStorageDirectory(),
                            IMAGE_FILE_NAME);
                    cropRawPhoto(Uri.fromFile(tempFile));
                } else {
                    Toast.makeText(getApplication(), "没有SDCard!", Toast.LENGTH_LONG)
                            .show();
                }
                break;
            case 400:
                if (data != null) {
                    Bundle extras = data.getExtras();
                    if (extras != null) {
                        Bitmap photo = extras.getParcelable("data");
                        File picture = new File(Environment.getExternalStorageDirectory(),
                                IMAGE_FILE_NAME);
                        try {
                            if (!picture.exists()) {
                                picture.createNewFile();
                            }
                            BufferedOutputStream bos = new BufferedOutputStream(
                                    new FileOutputStream(picture));
                            photo.compress(Bitmap.CompressFormat.PNG, 100, bos);
                            bos.flush();
                            bos.close();
                            sendImage(picture.getAbsolutePath());
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
                break;
            case 500:
                if (data != null) {
                    Uri picture = data.getData();
                    if (picture != null) {
                        sendFileByUri(picture);
                    }
                }
                break;
            case 600:
                if (data != null) {
                    PoiInfo info = data.getParcelableExtra("sendLocation");
                    Log.i("android", info + "------------------->>>>>>>>>2");
                    if (info != null) {
                        sendLocation(info);
                    }
                }
                break;
        }
    }


    /***************************************************图片*****************************************************************/


    /************************************************ 表情********************************************************************/

    /**
     * 表情页的监听事件
     */
    private OnCorpusSelectedListener mListener;

    /**
     * 显示表情页的viewpager
     */
    private ViewPager vp_face;

    /**
     * 表情页界面集合
     */
    private ArrayList<View> pageViews;

    /**
     * 游标显示布局
     */
    private LinearLayout layout_point;

    /**
     * 游标点集合
     */
    private ArrayList<ImageView> pointViews;

    /**
     * 表情集合
     */
    private List<List<ChatEmoji>> emojis;

    /**
     * 表情区域
     */
    private View view;

    /**
     * 表情数据填充器
     */
    private List<FaceAdapter> faceAdapters;

    /**
     * 当前表情页
     */
    private int current = 0;


    @Bind(R.id.biaoqingIv)
    ImageView biaoqingIv;


    @OnClick(R.id.biaoqingIv)
    void biaoqingIv(View v) {
        if (view.getVisibility() == View.VISIBLE) {

            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
            mInputMethodManager.showSoftInput(chattext, InputMethodManager.HIDE_NOT_ALWAYS);
            view.setVisibility(View.GONE);

        } else {

            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
            mInputMethodManager.hideSoftInputFromWindow(chattext.getWindowToken(), 0);
            recyclerView.setVisibility(View.GONE);
            view.setVisibility(View.VISIBLE);
        }
    }

    @OnClick(R.id.chattext)
    void chattext() {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        mInputMethodManager.showSoftInput(chattext, InputMethodManager.HIDE_NOT_ALWAYS);
        view.setVisibility(View.GONE);
    }


    public void setOnCorpusSelectedListener(OnCorpusSelectedListener listener) {
        mListener = listener;
    }


    public interface OnCorpusSelectedListener {

        void onCorpusSelected(ChatEmoji emoji);

        void onCorpusDeleted();
    }

    private void onCreate() {
        Init_View();
        Init_viewPager();
        Init_Point();
        Init_Data();
    }

    /**
     * 初始化控件
     */
    private void Init_View() {
        vp_face = (ViewPager) findViewById(R.id.vp_contains);
        chattext = (EditText) findViewById(R.id.chattext);
        layout_point = (LinearLayout) findViewById(R.id.iv_image);
        // chattext.setOnClickListener(this);
    }

    private void Init_viewPager() {
        pageViews = new ArrayList<View>();
        // 左侧添加空页
        View nullView1 = new View(this);
        // 设置透明背景
        nullView1.setBackgroundColor(0x00000000);
        pageViews.add(nullView1);

        // 中间添加表情页

        faceAdapters = new ArrayList<FaceAdapter>();
        for (int i = 0; i < emojis.size(); i++) {
            GridView view = new GridView(this);
            FaceAdapter adapter = new FaceAdapter(this, emojis.get(i));
            view.setAdapter(adapter);
            faceAdapters.add(adapter);
            view.setOnItemClickListener(this);
            view.setNumColumns(7);
            view.setBackgroundColor(0x00000000);
            view.setHorizontalSpacing(1);
            view.setVerticalSpacing(1);
            view.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
            view.setCacheColorHint(0);
            view.setPadding(5, 0, 5, 0);
            view.setSelector(new ColorDrawable(0x00000000));
            view.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT));
            view.setGravity(Gravity.CENTER);
            pageViews.add(view);
        }

        // 右侧添加空页面
        View nullView2 = new View(this);
        // 设置透明背景
        nullView2.setBackgroundColor(0x00000000);
        pageViews.add(nullView2);
    }

    /**
     * 初始化游标
     */
    private void Init_Point() {

        pointViews = new ArrayList<ImageView>();
        ImageView imageView;
        for (int i = 0; i < pageViews.size(); i++) {
            imageView = new ImageView(this);
            imageView.setBackgroundResource(R.mipmap.d1);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                    new ViewGroup.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                            LinearLayout.LayoutParams.WRAP_CONTENT));
            layoutParams.leftMargin = 10;
            layoutParams.rightMargin = 10;
            layoutParams.width = 8;
            layoutParams.height = 8;
            layout_point.addView(imageView, layoutParams);
            if (i == 0 || i == pageViews.size() - 1) {
                imageView.setVisibility(View.GONE);
            }
            if (i == 1) {
                imageView.setBackgroundResource(R.mipmap.d2);
            }
            pointViews.add(imageView);

        }
    }

    /**
     * 填充数据
     */
    private void Init_Data() {
        vp_face.setAdapter(new ViewPagerAdapter(pageViews));

        vp_face.setCurrentItem(1);
        current = 0;
        vp_face.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                current = arg0 - 1;
                // 描绘分页点
                draw_Point(arg0);
                // 如果是第一屏或者是最后一屏禁止滑动，其实这里实现的是如果滑动的是第一屏则跳转至第二屏，如果是最后一屏则跳转到倒数第二屏.
                if (arg0 == pointViews.size() - 1 || arg0 == 0) {
                    if (arg0 == 0) {
                        vp_face.setCurrentItem(arg0 + 1);// 第二屏 会再次实现该回调方法实现跳转.
                        pointViews.get(1).setBackgroundResource(R.mipmap.d2);
                    } else {
                        vp_face.setCurrentItem(arg0 - 1);// 倒数第二屏
                        pointViews.get(arg0 - 1).setBackgroundResource(
                                R.mipmap.d2);
                    }
                }
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });

    }

    /**
     * 绘制游标背景
     */
    public void draw_Point(int index) {
        for (int i = 1; i < pointViews.size(); i++) {
            if (index == i) {
                pointViews.get(i).setBackgroundResource(R.mipmap.d2);
            } else {
                pointViews.get(i).setBackgroundResource(R.mipmap.d1);
            }
        }
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        ChatEmoji emoji = (ChatEmoji) faceAdapters.get(current).getItem(arg2);
        if (emoji.getId() == R.drawable.face_del_icon) {
            int selection = chattext.getSelectionStart();
            String text = chattext.getText().toString();
            if (selection > 0) {
                String text2 = text.substring(selection - 1);
                if ("]".equals(text2)) {
                    int start = text.lastIndexOf("[");
                    int end = selection;
                    chattext.getText().delete(start, end);
                    return;
                }
                chattext.getText().delete(selection - 1, selection);
            }
        }
        if (!TextUtils.isEmpty(emoji.getCharacter())) {
            if (mListener != null)
                mListener.onCorpusSelected(emoji);
            SpannableString spannableString = FaceConversionUtil.getInstace()
                    .addFace(this, emoji.getId(), emoji.getCharacter());
            chattext.append(spannableString);
        }

    }

    /*********************************************************************************************/

    @Override
    protected void onDestroy() {
        super.onDestroy();

        /** 关闭软键盘 **/
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        mInputMethodManager.hideSoftInputFromWindow(chattext.getWindowToken(), 0);
    }

    @Override
    protected void onResume() {
        super.onResume();
        refresh();
    }


}


